package expression

import (
	"fmt"
	"log/slog"
	"rule/pkg/govaluate"
)

// calc expression , expression 是格式化后的数据 "1 > 0"
func calcExpression(expression string) (bool, error) {
	defer func() {
		if e := recover(); e != nil {
			slog.Error("CalcExpression_error", "e", e)
		}
	}()
	evaluableExpression, err1 := govaluate.NewEvaluableExpression(expression)
	if err1 != nil {
		return false, err1
	}
	result, err2 := evaluableExpression.Eval(nil)
	if err2 != nil {
		return false, err2
	}
	//
	ret, _ := result.(bool)
	return ret, nil
}

// "%v > 0" , val 是 int或string
func CalcExpressionWithValue(format string, val any) (bool, error) {
	expression := fmt.Sprintf(format, val)
	return calcExpression(expression)
}

func CalcBoolean(boolExpr string, p map[string]any) bool {
	evaluableExpression, err1 := govaluate.NewEvaluableExpression(boolExpr)
	if err1 != nil {
		return false
	}
	result, err2 := evaluableExpression.Evaluate(p)
	if err2 != nil {
		return false
	}
	//
	ret, _ := result.(bool)
	return ret
}
